import base64
import os
import uuid

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from rest_framework import serializers
from .models import Asset


class AssetSerializer(serializers.ModelSerializer):
    """
    资源展示序列化器，用于返回完整的资源信息
    """

    class Meta:
        model = Asset
        fields = '__all__'
        read_only_fields = (
            'id', 'created_at', 'url', 'original_filename', 'file_size', 'mime_type'
        )


class CreateAssetSerializer(serializers.ModelSerializer):
    """
    资源创建序列化器（支持Base64批量上传）
    """
    file_data = serializers.CharField(write_only=True, required=True,
                                      help_text="Base64编码的文件数据（示例：...）")
    original_filename = serializers.CharField(write_only=True, required=True, help_text="原始文件名")

    class Meta:
        model = Asset
        fields = [
            'project',
            'type',
            'width',
            'height',
            'file_data',
            'original_filename',
        ]
        extra_kwargs = {
            'width': {'required': False},
            'height': {'required': False},
        }

    def validate_file_data(self, value):
        """Base64文件解码验证"""
        try:
            # 分离数据头与内容
            header, data = value.split(';base64,')
            mime_type = header.split(':')[-1]

            # 验证MIME类型
            allowed_types = [
                'image/jpeg',
                'image/png',
                'font/ttf',
                'font/woff',
                'application/octet-stream'
            ]
            if mime_type not in allowed_types:
                raise serializers.ValidationError("不支持的文件类型")

            # 解码数据
            decoded_file = base64.b64decode(data)

            # 验证文件大小（5MB）
            if len(decoded_file) > 5 * 1024 * 1024:
                raise serializers.ValidationError("文件大小超过5MB")

            return {
                'data': decoded_file,
                'mime_type': mime_type,
            }
        except ValueError:
            raise serializers.ValidationError("无效的Base64格式")
        except Exception as e:
            raise serializers.ValidationError(f"文件解析失败: {str(e)}")

    def create(self, validated_data):
        """处理文件存储"""
        file_info = validated_data.pop('file_data')
        original_name = validated_data.pop('original_filename')
        mime_type = file_info['mime_type']
        file_data = file_info['data']

        # 生成存储路径
        file_ext = os.path.splitext(original_name)[1]
        if not file_ext:  # 无扩展名时根据MIME类型推断
            file_ext = {
                'image/jpeg': '.jpg',
                'image/png': '.png',
                'font/ttf': '.ttf',
                'font/woff': '.woff'
            }.get(mime_type, '.bin')

        # 构建存储路径
        file_type = validated_data['type']
        filename = f"{uuid.uuid4()}{file_ext}"
        storage_path = f"assets/{file_type}/{filename}"

        # 保存文件
        default_storage.save(storage_path, ContentFile(file_data))

        # 构建完整数据
        asset_data = {
            **validated_data,
            "url": storage_path,
            "original_filename": original_name,
            "file_size": len(file_data),
            "mime_type": mime_type,
            "thumbnail_url": storage_path,  # 实际项目需单独生成缩略图
            "optimized_url": storage_path  # 实际项目需单独优化处理
        }
        return super().create(asset_data)


class BulkCreateAssetSerializer(CreateAssetSerializer):
    """批量创建继承相同逻辑"""

    class Meta(CreateAssetSerializer.Meta):
        pass


class SaveAssetSerializer(serializers.ModelSerializer):
    """
    资源创建序列化器，创建时只需要提供关联项目和资源类型，
    文件相关信息由视图在处理上传后填充
    """

    class Meta:
        model = Asset
        fields = [
            'project',  # 关联项目
            'type',  # 资源类型（background/mask/font）
            'url',
            'original_filename',
            'file_size',
            'mime_type',
            'width',
            'height',
            'thumbnail_url',
            'optimized_url',
        ]

        extra_kwargs = {
            'width': {'required': False},
            'height': {'required': False},
        }


class UpdateAssetSerializer(serializers.ModelSerializer):
    """
    资源更新序列化器，用于更新资源的其他信息（不包含文件更新部分）
    """

    class Meta:
        model = Asset
        fields = [
            'type',  # 允许更新资源类型
            'width',
            'height',
        ]
        extra_kwargs = {
            'width': {'required': False},
            'height': {'required': False},
        }
